package org.shoukaiseki.inittable.domain;

/**
 * 限制,外键限制
 *
 * 简单命名
 * fk_[当前表名称]_[当前列名]
 *
 * fk_[当前表名称]_[引用的表名称]_[当前列名]
 *
 *
 * CREATE TABLE users(
 *  user_id int,
 *  name varchar(100)
 * );
 *
 * CREATE TABLE messages(
 *  message_id int,
 *  user_id int
 * );
 *
 * ALTER TABLE messages ADD CONSTRAINT fk_messages_users_user_id
 *  FOREIGN KEY (user_id) REFERENCES users(user_id);
 */
public  class TableConstraintForeignKeyInfo extends TableConstraintInfo{

    /**
     * 当前表的关联字段
     */
    private String columnName;

    /**
     * 关联的表名
     */
    private String relationTableName;

    /**
     * 关联表的的属性名
     */
    private String relationColumnName;

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getRelationTableName() {
        return relationTableName;
    }

    public void setRelationTableName(String relationTableName) {
        this.relationTableName = relationTableName;
    }

    public String getRelationColumnName() {
        return relationColumnName;
    }

    public void setRelationColumnName(String relationColumnName) {
        this.relationColumnName = relationColumnName;
    }

    /**
     * 生成限制sql
     * @param tableName
     * @return
     */
    public String buildAddSql(String tableName){
        StringBuilder sb=new StringBuilder();
        sb.append("alter table `").append(tableName).append("`")
                .append(" add constraint `").append(this.getConstraintName()).append("`")
                .append(" foreign key (`").append(this.relationColumnName).append("`) references ")
                .append("`").append(relationTableName).append("`").append(" (`").append(relationColumnName).append("`)");
        return sb.toString();
    }


}
